package com.example.jsondemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Student student1 = new Student("Jack",20);
        Gson gson = new Gson();
        Student student2 = new Student("Tom",21,new Score(95,85,92));
        String jsonStudent2 = gson.toJson(student2);

        //String jsonStudent1 = gson.toJson(student1);   //利用gson序列化

        //String jsonStudent1 = "{\"age\":20,\"name\":\"Jack\"}";
        //Student student1 = gson.fromJson(jsonStudent1,Student.class);   //反序列化

        //示例2
//        Student student3 = new Student("H",21,new Score(87,90,67));
//        Student student4 = new Student("Q",18,new Score(96,94,92));
        List<Student> studentList = new ArrayList<>();
//        studentList.add(student3);
//        studentList.add(student4);
        String jsonStudents = "[{\"age\":21,\"name\":\"H\",\"score\":{\"chinese\":67,\"english\":90,\"math\":87}},{\"age\":18,\"name\":\"Q\",\"score\":{\"chinese\":92,\"english\":94,\"math\":96}}]";
        Type typeStudents = new TypeToken<List<Student>>(){}.getType();   //创建一个新的类型
        studentList = gson.fromJson(jsonStudents,typeStudents);   //反序列化
    }
}